package Demo3;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-06-05
 * Time: 18:55
 */
public class ArrayList implements IList{
    public int[] array;
    public int useSize;
    public static final int COUNT = 5;

    public ArrayList(){
        array = new int[COUNT];
    }


    @Override
    public boolean isFull() {
        return this.array.length == useSize;
    }

    //扩容
    public void Expansion(){
        this.array = Arrays.copyOf(this.array,2 * this.array.length);
    }

    public void add(int data) {
        if(isFull()){//判断数组是否满？扩容：直接赋值
            Expansion();
        }
        this.array[useSize++] = data;
    }

    public void posCheck1(int pos) throws PosException1 {
        if(pos < 0 || pos > this.useSize){
            throw new PosException1("pos位置不合法");
        }
    }

    public void posCheck2(int pos) throws PosException2{
        if(pos < 0 || pos >= this.useSize){
            throw new PosException2("pos位置不合法");
        }
    }

    @Override
    public void add(int pos, int data) throws PosException1 {
        try{
            posCheck1(pos);
            if(isFull()){//判断数组是否满？扩容：直接赋值
                Expansion();
            }
            for (int i = this.useSize - 1; i >= pos; i--) {
                this.array[i + 1] = this.array[i];
            }
            this.array[pos] = data;
            this.useSize++;
        }
        catch(PosException1 e){
            e.printStackTrace();
        }

    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < this.array.length; i++) {
            if(this.array[i] == toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < this.array.length; i++) {
            if(this.array[i] == toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        try{
            posCheck2(pos);
        }catch(PosException1 e){
            e.printStackTrace();
        }
        return this.array[pos];
    }

    @Override
    public void set(int pos, int value) {

    }

    @Override
    public void remove(int toRemove) {

    }

    @Override
    public int size() {
        return this.useSize;
    }

    @Override
    public void clear() {

    }

    @Override
    public void display() {
        for (int i = 0; i < this.array.length; i++) {
            System.out.print(this.array[i] + " ");
        }
        System.out.println();
    }
}
